/**
 * 商品详情
 */
var offerId = getURLParameter('goodId');
var startSaleNum = 0;

var DetailHeader = React.createClass({
    sendShareApp: function(){
        //#send   调用window.frontshoes.shareApp("","",图片数组，"当前页面地址");
        window.frontshoes.shareApp("","",this.props.imgs.join(','),"http://120.77.86.178:41200/src/detail.html?goodId="+offerId);
    },
    render: function(){
        return (
            <header data-am-widget="header" className="am-header am-header-default am-header-fixed">
                <div className="am-header-left am-header-nav">
                    <a onClick={this.props.back}><i className="icon_8"></i></a>
                </div>
                <h1 className="am-header-title">商品详情</h1>
                <div className="am-header-right am-header-nav am-dropdown" id="am-dropdown">
                    <a href="cart.html" ><i className="ShoppingCart_3"></i></a>
                    <i className="send" onClick={this.sendShareApp}></i>
                    <div className="am-dropdown-toggle icontopmore" id="am-dropdown-toggle"></div>
                    <ul className="am-dropdown-content">
                        <li className="padding-left-20"><a href="index.html" className="font-color-45 prelative">首页</a></li>
                        <li className="am-divider"></li>
                        <li className="padding-left-20"><a href="personal.html" className ="font-color-45 prelative">个人中心</a></li>
                    </ul>
                </div>
            </header>
        )
    }
});

function createHTML(html) {
    return {__html: html};
}
//主要内容主体
var DetailMain = React.createClass({
    componentDidMount: function(){
        $('.am-slider-default').flexslider({ });
    },
    render: function(){
        var imgsArr = [], colorsArr = [], lengthsArr = [];
        this.props.imgs.forEach(function(value){
            imgsArr.push(<li><img src={value}/></li>);
        });
        this.props.colors.forEach(function(value){
            colorsArr.push(value.spec_value);
        });
        this.props.lengths.forEach(function(value){
            lengthsArr.push(value.spec_value);
        });
        // <div data-am-widget="slider" class="am-slider am-slider-default" data-am-slider='{}'>
        //     <ul class="am-slides">
        //         <li>
        //             <img src="assets/images/icons/pic_3.png">
        //         </li>
        //         <li>
        //             <img src="assets/images/icons/pic_3.png">
        //         </li>
        //         <li>
        //             <img src="assets/images/icons/pic_3.png">
        //         </li>
        //
        //     </ul>
        // </div>
        return (
            <section data-tag="css-nav">
                <div className="prelative">
                    <div data-am-widget="slider" className="am-slider am-slider-default" data-am-slider='{}'>
                        <ul className="am-slides">{imgsArr}</ul>
                    </div>
                </div>
                <div className="am-padding-left-sm am-padding-right-sm bg-white am-margin-bottom-sm">
                    <div className="am-padding-top-sm am-padding-bottom-sm ">
                        <div>
                            <div className="box"><div className="font-color-2 am-padding-right-xs">{this.props.name}</div></div>
                            <div className="padding-top-5 box">
                                <div className="box-1"><span className="font-18 font-color-monney">&yen;{this.props.price}</span></div>
                                <div className="font-color-1 font-14 padding-top-3px">已售：{this.props.saleCnt}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="bg-white am-margin-top-sm">
                    <div data-am-widget="titlebar" className="am-titlebar am-titlebar-default box prelative">
                        <i className="bgmainblock"></i><h2 className="am-titlebar-title box-1">商品信息</h2>
                    </div>
                </div>
                <div className="am-padding-left-sm am-padding-right-sm bg-white">
                    <div className="am-padding-left-sm bg-white am-cf border-tops am-padding-top-sm">
                        <div className="resou">
                            <ul>
                                <li><a className="dis">品牌：{this.props.brandDesc}</a></li>
                                <li><a className="dis">分类：{this.props.typeDesc}</a></li>
                                <li><a className="dis">颜色：{colorsArr.join('，')}</a></li>
                                <li><a className="dis">码数：{lengthsArr.join('，')}</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div className="bg-white am-margin-top-sm">
                    <div data-am-widget="titlebar" className="am-titlebar am-titlebar-default box prelative">
                        <i className="bgmainblock"></i><h2 className="am-titlebar-title box-1">商品详情</h2>
                    </div>
                </div>
                <div className="bg-white am-margin-bottom-0">
                    <div className="good_detail" dangerouslySetInnerHTML={createHTML(this.props.detail)} />
                </div>
            </section>
        )
    }
});

var DetailFooter = React.createClass({
    handleOpenClick: function(e){
        $('#my-popup').modal('open');
        e.stopPropagation();
        e.preventDefault();
    },
    handleKeepClick: function(e){
        if(this.props.isKeep){
            this.props.cancelKeep();
        }else {
            this.props.keep();
        }
        e.stopPropagation();
        e.preventDefault();
    },
    handleRedirectClick: function() {
        $.ajax(
            getAjaxOps('/config/getQQ', {})
        ).done(function (res) {
            if(res.resultCode == 0){
                window.frontshoes.chat(res.data.toString());
            }
        }.bind(this));
        // location.href = 'mqqwpa://im/chat?chat_type=wpa&uin=348757652&version=1&src_type=web&web_src=bjhuli.com';
    },
    render: function(){
        return (
            <footer data-am-widget="navbar" className="am-navbar am-cf am-navbar-default">
                <ul className="am-navbar-nav am-cf am-avg-sm-4 am-padding-right-0 ">
                    <li>
                        <a className={ this.props.isKeep ? 'piccollect cur' : 'piccollect'} onClick={this.handleKeepClick}>
                            <img src="../assets/images/icons/Collect.png" alt=""/>
                            <span className="am-navbar-label font-color-1">{ this.props.isKeep ? '取消关注' : '关注'}</span>
                        </a>
                    </li>
                    <li><a onClick={this.handleRedirectClick}><img src="../assets/images/icons/qq.png" alt="客服"/><span className="am-navbar-label font-color-1">客服</span></a></li>
                    <li><a onClick={this.handleOpenClick} className="bg-2 font-color-white font-15 line-51">去下单</a></li>
                </ul>
            </footer>
        )
    }
});

var ChooseItem = function (props) {
    return (
        <div className="box am-padding-top-ss am-padding-bottom-ss border-bottom">
            <div className="am-padding-left-sm width-100px">{props.color}</div>
            <div className="am-padding-left-sm width-100px">{props.length}</div>
            <div className="box-1">
                <div className="box">
                    <div className="goodjian am-margin-right-sm"></div>
                    <div className="goodnum" data-id={props.cId + '-' + props.sId}>{props.num}</div>
                    <div className="goodjia am-margin-left-sm am-margin-right-sm"></div>
                </div>
            </div>
        </div>
    )
};
//选择商品规格
var ChooseBox = React.createClass({
    getInitialState: function(){
        return {
            curIndex: 0,
            specs: Immutable.Map({})
        }
    },
    handleAddClick: function(e){
        $('#my-popup').modal('close');
        var cartSpecs = [];
        this.state.specs.map(function(value, key){
            cartSpecs.push({
                'color': key.split('-')[0],
                'length': key.split('-')[1],
                'number': value
            })
        });
        this.props.addToCart({
            offerId: offerId,
            specs: cartSpecs
        });
        e.stopPropagation();
        e.preventDefault();
    },
    handleChangeClick: function(e){
        var target = e.target;
        if(target.nodeName === 'A'){
            var id = parseInt(target.getAttribute('data-index')),
                value = target.getAttribute('data-value');
            this.setState({
                curIndex: id
            })
        }
        e.stopPropagation();
        e.preventDefault();
    },
    handleGoodNumClick: function(e) {
        var target = e.target,num = null;
        if(target.className.indexOf('goodjian') >= 0){
            //减少
            num = target.nextElementSibling;
            var count = parseInt(num.innerHTML);
            if(count > 0) {
                num.innerHTML = --count;
                if(count === 0){
                    //数量减为0 删除该商品
                    this.setState({
                        specs: this.state.specs.delete(num.getAttribute('data-id'))
                    });
                }else{
                    //update 数量
                    this.setState({
                        specs: this.state.specs.update(num.getAttribute('data-id'), function(){return count;})
                    });
                }
            }
        }else if(target.className.indexOf('goodjia') >= 0){
            //添加
            num = target.previousElementSibling;
            var count = parseInt(num.innerHTML);
            num.innerHTML = ++count;
            this.setState({
                specs: this.state.specs.update(num.getAttribute('data-id'), function(){return count;})
            });
        }
        e.stopPropagation();
        e.preventDefault();
    },
    render: function(){
        var styleObj = {'height': '75%', 'top': '25%', 'bottom': '0'},
            styleObj2 = {'position': 'absolute', 'width': '100%', 'bottom': '0', 'padding-top': '0px', 'padding-bottom': '49px'};
        var colorsArr = [], itemsArr = [], selectedArr = [],
            l = this.props.colors.length, l2 = this.props.lengths.length,
            curTotal = 0;
        //选择框颜色、鞋码
        for(var i = 0; i < l ; i++){
            var cId = this.props.colors[i].id, color = this.props.colors[i].spec_value;
            colorsArr.push(<li><a className={i == this.state.curIndex ? 'cur': ''} data-index={i} data-value={color}>{color}</a></li>);

            for(var j = 0; j < l2; j++){
                var sId = this.props.lengths[j].id,
                    size = this.props.lengths[j].spec_value,
                    count = this.state.specs.get(cId + '-' + sId);
                //已选的颜色、鞋码
                if(count && (count = parseInt(count)) > 0){
                    selectedArr.push(<div>{color}，{size}码，{count}双;</div>);
                }else {
                    count = 0;
                }
                curTotal += count;

                if(i == this.state.curIndex) {
                    itemsArr.push(<ChooseItem cId={cId} color={color} sId={sId} length={size} num={count}/>);
                }
            }
        }
        return (
            <div className="am-popup" id="my-popup" style={styleObj}>
                <div className="am-popup-inner" style={styleObj2}>
                    <i className="icon-guanbi" data-am-modal-close style={{'top': '10px'}}></i>
                    <div className="am-popup-bd am-padding-left-0 am-padding-right-0">
                        <div className="am-padding-left-sm am-padding-right-sm">
                            <div className="box">
                                <div className="width-100px prelative" style={{'background-color': '#fff'}}>
                                    <img className="width-100px border-radius-5" src={this.props.img}/>
                                </div>
                                <div className="box-1 am-margin-top-sm am-margin-left-sm am-padding-top-sm">
                                    <div className="font-color-monney">&yen;{parseFloat(this.props.price).toFixed(2)}</div>
                                    <div className="am-text-truncate font-color-2">{this.props.name}</div>
                                </div>
                            </div>
                            <div className="box am-padding-sm border-tops am-margin-top-sm am-padding-left-0  am-cf am-padding-bottom-0">
                                <div className="font-color-2 padding-top-1">已选</div>
                                <div className="font-color-1 box-1 am-margin-left-sm">
                                    <div className="resou">
                                        <ul onClick={this.handleChangeClick}>{colorsArr}</ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="bg-white font-color-1" onClick={this.handleGoodNumClick}>
                            <div className="box am-padding-top-ss am-padding-bottom-ss bg-gray">
                                <div className="am-padding-left-sm width-100px">颜色</div>
                                <div className="am-padding-left-sm width-100px">码数</div>
                                <div className="box-1">购买数量</div>
                            </div>
                            {itemsArr}
                        </div>
                        <div className="box am-padding-sm">
                            <div className="font-color-2">已选</div>
                            <div className="font-color-1 box-1 am-margin-left-sm">{selectedArr}</div>
                        </div>
                    </div>
                </div>
                <footer data-am-widget="navbar" className="am-navbar am-cf am-navbar-default">
                    <ul className="am-navbar-nav am-cf am-avg-sm-4 am-padding-right-0">
                        <li>
                            <a className="am-text-left">
                                <span className="font-color-monney">&yen;{parseFloat(this.props.price * curTotal).toFixed(2)} </span>
                                <span className="font-14 font-color-2"> 共{curTotal}件</span>
                            </a>
                        </li>
                        <li>
                            <a onClick={this.handleAddClick} className="bg-2 font-color-white font-15 line-51">加入购物车</a>
                        </li>
                    </ul>
                </footer>
            </div>
        )
    }
});

var Page = React.createClass({
    getInitialState: function(){
        return{
            name: '',
            price: '',
            imgs: [],
            colors: [],
            lengths: [],
            detail: '',
            isKeep: '',
            brandDesc: '',
            typeDesc: '',
            saleCnt: 0,
            msgHidden: true,
            msg: ''
        }
    },
    componentWillMount: function(){
        $.ajax(
            getAjaxOps('/offer/getOfferDetailForApp', {
                offerId: offerId,
                userId: USER.userId
            })
        ).done(function (res) {
                if(res.resultCode == 0){
                    this.setState({
                        name: res.data.offer_name,
                        price: res.data.market_id == null ? res.data.in_price : res.data.out_price,
                        imgs: res.data.imgs.map(function(value){
                            return IMG_PRE+value.url
                        }),
                        colors: res.data.colors,
                        lengths: res.data.lengths,
                        detail: res.data.detail.content,
                        isKeep: (res.data.keep == '1' ? true : false),
                        brandDesc: res.data.brandDesc,
                        typeDesc: res.data.typeDesc,
                        saleCnt: res.data.saleCnt
                    });
                    startSaleNum = +res.data.start_sale_num;
                    $('.am-slider-default').flexslider({ });
                }
            }.bind(this));
    },
    back: function(){
        history.go(-1);
    },
    keep: function() {
        if(getUser()){
            $.ajax(
                getAjaxOps('/offer/addKeep',{
                    userId: USER.userId,
                    offerId: offerId
                })
            ).done(function(res){
                    if(res.resultCode == 0){
                        this.setState({
                            isKeep: true
                        })
                    }
                }.bind(this));
        }
    },
    cancelKeep: function() {
        if(getUser()){
            $.ajax(
                getAjaxOps('/offer/removeKeep',{
                    userId: USER.userId,
                    offerId: offerId
                })
            ).done(function(res){
                    if(res.resultCode == 0){
                        this.setState({
                            isKeep: false
                        })
                    }
                }.bind(this));
        }
    },
    addToCart: function(data) {
        var count = 0;
        data.specs.forEach(function(spec){
            count += spec.number;
        });
        if(count === 0){
            this.setState({
                msgHidden: false,
                msg: '商品购买数不能为0'
            });
            return false;
        }else if(count < startSaleNum){
            this.setState({
                msgHidden: false,
                msg: '商品起售数量为'+startSaleNum
            });
            return false;
        }
        if(ifUser()){
            data.userId = USER.userId;
            $.ajax(
                getAjaxOps('/cart/addItem', {"itemStr":JSON.stringify(data)})
            ).done(function (res) {
                if(res.resultCode == 0){
                    location.href = 'cart.html';
                }else {
                    this.setState({
                        msgHidden: false,
                        msg: res.resultMsg
                    });
                }
            }.bind(this));
        }
    },
    closeMsg: function() {
        this.setState({
            msgHidden: true
        });
    },
    render: function() {
        return (
            <div>
                <DetailHeader back={this.back} imgs={this.state.imgs} />
                <DetailMain imgs={this.state.imgs} colors={this.state.colors} lengths={this.state.lengths}
                            name={this.state.name} price={this.state.price} detail={this.state.detail}
                            saleCnt={this.state.saleCnt} brandDesc={this.state.brandDesc} typeDesc={this.state.typeDesc} />
                <DetailFooter isKeep={this.state.isKeep} keep={this.keep} cancelKeep={this.cancelKeep}/>
                <ChooseBox price={this.state.price} colors={this.state.colors} lengths={this.state.lengths} img={this.state.imgs[0]} addToCart={this.addToCart} />
                <Message hidden={this.state.msgHidden} msg={this.state.msg}  close={this.closeMsg} />
            </div>
        )
    }
});

ReactDOM.render(
    <Page />,
    document.getElementById('root')
);